package main.java.utils.common;

import lombok.Getter;

import java.util.function.Consumer;

public class Progress extends Thread {
	@Getter protected long current, startTime, total, interval;
	protected String message;
	protected Consumer<String> logger;

	public Progress(String message, long total, long interval, Consumer<String> logger) {
		this.total = total;
		this.interval = interval;
		this.message = message;
		this.logger = logger;
		setDaemon(true);
	}

	protected void beforePrint() {
	}

	public void increase(long delta) {
		if (startTime == 0) {
			startTime = System.currentTimeMillis();
		}
		current += delta;
	}

	public boolean isFinished() {
		return current == total;
	}

	@Override
	public void run() {
		try {
			for (; current < total && !Thread.currentThread().isInterrupted(); ) {
				beforePrint();
				if (startTime != 0) {
					long percentage = 100 * current / total;
					long elapsed = System.currentTimeMillis() - startTime;
					long remaining = current != 0 ? elapsed * (total - current) / current : 0;
					logger.accept(String.format("[%s] - %d%% (%s/%s), time elapsed: %ss, time remaining: %ss", message, percentage, current, total, elapsed / 1000, remaining / 1000));
				}
				sleep(interval);
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
		long elapsed = System.currentTimeMillis() - startTime;
		logger.accept(String.format("%s - time elapsed: %ss", message, elapsed / 1000));
	}

	public void setProgress(long current) {
		if (startTime == 0) {
			startTime = System.currentTimeMillis();
		}
		this.current = current;
	}
}
